package cn.harmonyoslearn.navrouter.dialog;

import cn.harmonyoslearn.navrouter.datas.NavName;
import cn.harmonyoslearn.navrouter.datas.PageOrDialogInfo;
import cn.harmonyoslearn.navrouter.models.ServiceModel;
import cn.harmonyoslearn.navrouter.utils.LogUtil;
import cn.harmonyoslearn.navrouter.utils.NotificationUtil;
import cn.harmonyoslearn.navrouter.utils.StringUtil;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.DialogWrapper;
import groovyjarjarantlr4.v4.runtime.misc.Nullable;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Objects;

/**
 * 新建Navigation页面弹窗
 */
public class NewNavigationPageDialog extends DialogWrapper {
    /**
     * 窗口容器
     */
    private JPanel myPanel;
    /**
     * 是否显示默认标题按钮
     */
    private JPanel isTittlePanel;
    /**
     * 图片组件
     */
    private JPanel imagePanel;
    /**
     * 页面类型
     */
    private PageType pageType = PageType.PAGE;
    /**
     * 是否展示默认标题栏
     */
    private Boolean isTittle = true;
    /**
     * 名称是否重复
     */
    private Boolean isRepeat = true;

    /**
     * 页面类型
     * PAGE 页面类型
     * DIALOG 弹窗类型
     */
    public enum PageType {
        /**
         * 页面类型
         */
        PAGE,
        /**
         * 弹窗类型
         */
        DIALOG
    }

    private JTextField pageNameField;
    private JTextField noteField;
    private JPanel infoPanel;

    AnActionEvent anActionEvent;

    public NewNavigationPageDialog(@NotNull AnActionEvent e) {
        super(true);
        init();
        this.anActionEvent = e;
        setTitle("新建Navigation页面");
    }

    @Override
    protected void doOKAction() {
        if (this.isRepeat) {
            NotificationUtil.showMessageDialog("错误提示", "名称重复了");
            return;
        }
        super.doOKAction();
    }

    public void setType(PageType type) {
        pageType = type;
        LogUtil.i("NewNavigationPageDialog.setType", "setType is " + type);

        // 替换是否展示默认显示标题选项
        isTittlePanel.removeAll();
        isTittlePanel.add(getIsTittlePanel());
        isTittlePanel.revalidate(); // 通知容器重新布局其子组件
        isTittlePanel.repaint();    // 重新绘制面板
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        if (myPanel == null) {
            setPanel();
        }
        return myPanel;
    }

    /**
     * 获取输入结果
     */
    public PageOrDialogInfo getInputData() {
        return new PageOrDialogInfo(isTittle, pageType, pageNameField.getText(), noteField.getText());
    }

    /**
     * 设置容器组件内容
     */
    public void setPanel() {
        myPanel = new JPanel();
        // 设置布局管理器为 BoxLayout，并指定为垂直方向
        myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));
        myPanel.add(Box.createVerticalStrut(15));

        myPanel.add(getPageNamePanel(), Component.LEFT_ALIGNMENT);
        myPanel.add(Box.createVerticalStrut(15));
        myPanel.add(getNotePanel(), Component.LEFT_ALIGNMENT);
        myPanel.add(Box.createVerticalStrut(15));

        // 选择文件类型
        myPanel.add(getPageTypePanel());
        myPanel.add(Box.createVerticalStrut(15));

        // 选择是否使用系统默认标题栏
        isTittlePanel = new JPanel();
        isTittlePanel.setLayout(new BoxLayout(isTittlePanel, BoxLayout.X_AXIS));
        isTittlePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        isTittlePanel.add(getIsTittlePanel());
        myPanel.add(isTittlePanel);
        myPanel.add(Box.createVerticalStrut(15));
    }

    /**
     * 获取是否显示默认标题按钮
     */
    public JPanel getIsTittlePanel() {
        // 页面类型
        JPanel isTittlePanel = new JPanel();
        isTittlePanel.setLayout(new BoxLayout(isTittlePanel, BoxLayout.X_AXIS));
        isTittlePanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        if (pageType == PageType.PAGE) {
            // 选择是否展示标题栏弹窗
            JRadioButton radioButtonOnTittle = new JRadioButton("显示默认标题栏");
            radioButtonOnTittle.setSelected(true);
            JRadioButton radioButtonOffTittle = new JRadioButton("不显示默认标题栏");

            isTittlePanel.add(radioButtonOnTittle);
            isTittlePanel.add(Box.createHorizontalStrut(10));
            isTittlePanel.add(radioButtonOffTittle);

            // 创建按钮组，并将单选按钮添加到该组
            ButtonGroup buttonGroup = new ButtonGroup();
            buttonGroup.add(radioButtonOnTittle);
            buttonGroup.add(radioButtonOffTittle);

            // 添加 ItemListener 到 JRadioButtons
            ItemListener itemListener = e -> {
                JRadioButton radioButton = (JRadioButton) e.getSource();
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    String text = radioButton.getText();
                    this.isTittle = Objects.equals(text, "显示默认标题栏");
                }
            };

            radioButtonOnTittle.addItemListener(itemListener);
            radioButtonOffTittle.addItemListener(itemListener);
        } else {
            JLabel radioButtonOffTittle = new JLabel("弹窗没有标题栏");
            isTittlePanel.add(radioButtonOffTittle);
        }
        return isTittlePanel;
    }

    /**
     * 获取页面类型选择容器
     */
    public JPanel getPageTypePanel() {
        // 页面类型
        JPanel templateIdPanel = new JPanel();
        templateIdPanel.setLayout(new BoxLayout(templateIdPanel, BoxLayout.X_AXIS));
        templateIdPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 选择模式单选框
        JRadioButton radioButtonPage = new JRadioButton("Page");
        radioButtonPage.setSelected(true);
        JRadioButton radioButtonDialog = new JRadioButton("Dialog");

        // 将单选按钮添加到面板
        templateIdPanel.add(radioButtonPage);
        templateIdPanel.add(Box.createHorizontalStrut(10));
        templateIdPanel.add(radioButtonDialog);

        // 创建按钮组，并将单选按钮添加到该组
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(radioButtonPage);
        buttonGroup.add(radioButtonDialog);

        // 添加 ItemListener 到 JRadioButtons
        ItemListener itemListener = e -> {
            JRadioButton radioButton = (JRadioButton) e.getSource();
            if (e.getStateChange() == ItemEvent.SELECTED) {
                String text = radioButton.getText();

                switch (text) {
                    case "Page" -> setType(PageType.PAGE);
                    case "Dialog" -> setType(PageType.DIALOG);
                }
            }
        };

        radioButtonPage.addItemListener(itemListener);
        radioButtonDialog.addItemListener(itemListener);
        return templateIdPanel;
    }

    /**
     * 获取编辑页面名称容器
     */
    public JPanel getPageNamePanel() {
        // 页面名称
        JPanel pageNamePanel = new JPanel();
        pageNamePanel.setLayout(new BoxLayout(pageNamePanel, BoxLayout.X_AXIS));
        pageNamePanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel pageNameLabel = new JLabel("页面名称");
        pageNamePanel.add(pageNameLabel);
        pageNamePanel.add(Box.createHorizontalStrut(10));

        pageNameField = new JTextField(30);
        addSetNameListener(pageNameField);
        pageNamePanel.add(pageNameField);

        infoPanel = new JPanel();
        pageNamePanel.add(infoPanel);
        return pageNamePanel;
    }

    /**
     * 获取编辑注释容器
     */
    public JPanel getNotePanel() {
        // 页面名称
        JPanel notePanel = new JPanel();
        notePanel.setLayout(new BoxLayout(notePanel, BoxLayout.X_AXIS));
        notePanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel pageNameLabel = new JLabel("注      释");
        notePanel.add(pageNameLabel);
        notePanel.add(Box.createHorizontalStrut(10));

        noteField = new JTextField(30);
        notePanel.add(noteField);

        notePanel.add(new JPanel());
        return notePanel;
    }

    /**
     * 给文本输入框添加上输入约束，只能输入a-zA-Z0-9_
     */
    public void addSetNameListener(JTextField textField) {
        textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (textField.getText().isEmpty() && !Character.isLetter(c)) {
                    // 开头必须是英文字母
                    e.consume();
                } else if (StringUtil.isDigitOrLetterOr_(c)) {
                    // 只允许英文字母、数字和下划线
                    e.consume();
                }
            }
        });

        DocumentListener documentListener = new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                changeInfoPanel();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                changeInfoPanel();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
            }

            public void changeInfoPanel() {
                String name = textField.getText();

                try {
                    ArrayList<NavName> navNames = ServiceModel.getInstance().getNavNamesModel().getNavNames();

                    for (NavName navName : navNames) {
                        if (Objects.equals(name, navName.name)) {
                            isRepeat = true;
                            infoPanel.removeAll();
                            JLabel label = new JLabel("名称重复了");
                            infoPanel.add(label);
                            infoPanel.revalidate();
                            infoPanel.repaint();
                            myPanel.revalidate();
                            myPanel.repaint();
                            return;
                        }
                    }
                    isRepeat = false;
                    infoPanel.removeAll();
                    infoPanel.revalidate();
                    infoPanel.repaint();
                    myPanel.revalidate();
                    myPanel.repaint();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };

        textField.getDocument().addDocumentListener(documentListener);
    }
}